package com.cloud.form.api.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.form.api.entity.FormDef;
import com.cloud.form.api.service.FormDefService;
import com.cloud.form.common.result.Quokka;
import com.cloud.form.common.utils.WordHelper;

@RestController
@RequestMapping("/form/api/formdef")
public class FormDefController {

	@Autowired
	private FormDefService formDefService;

	@RequestMapping("/tree")
	public Quokka listBizFormTree() {
		return new Quokka(true, formDefService.listBizFormTree());
	}

	@RequestMapping("/detail")
	public Quokka detail(long id) {
		return new Quokka(true, formDefService.loadFormDefById(id));
	}

	@RequestMapping("/saveupdate")
	public Quokka create(@RequestBody FormDef formDef) {
		return new Quokka(true, formDefService.createUpdateForm(formDef));
	}

	@RequestMapping("/delete")
	public Quokka delete(long id) {
		return new Quokka(true, formDefService.deleteForm(id));
	}

	@RequestMapping("template/download")
	public ResponseEntity<byte[]> downloadTemplate(long formId) throws Exception {
		Map<String, String> result = formDefService.loadPrintForm(formId);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition",
				"attachment;filename=\"" + URLEncoder.encode(result.get("fileName") + ".doc", "utf-8") + "\"");
		return new ResponseEntity<byte[]>(Base64.getDecoder().decode(result.get("fileContent")), headers,
				HttpStatus.OK);
	}
	
	@RequestMapping("template/upload")
	public Quokka uploadTemplate(MultipartFile file, long formId) throws IOException{
		String fileContent = Base64.getEncoder().encodeToString(file.getBytes());
		formDefService.uploadTemplate(formId, fileContent);
		return new Quokka(true, formId);
	}
	
	@RequestMapping("loadprintform")
	public Quokka loadPrintForm(long id) {
		Map<String, String> result = formDefService.loadPrintForm(id);
		result.put("fileContent", Base64.getEncoder()
				.encodeToString(WordHelper.word2Pdf(Base64.getDecoder().decode(result.get("fileContent")))));
		return new Quokka(true, result);
	}

}
